package org.Lin.client;

import org.Lin.util.AESUtil;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;

public class FriendChatClient {
    private JFrame frame;
    private JTextArea chatArea;
    private JTextField inputField;
    private JComboBox<String> friendComboBox;

    public void show() {
        frame = new JFrame("好友私聊");
        frame.setSize(600, 400);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(chatArea);

        JPanel topPanel = new JPanel(new FlowLayout());
        topPanel.add(new JLabel("选择好友:"));
        friendComboBox = new JComboBox<>(new String[]{"好友A", "好友B", "好友C"});
        topPanel.add(friendComboBox);

        inputField = new JTextField();
        JButton sendButton = new JButton("发送");

        sendButton.addActionListener(e -> {
            String selectedFriend = (String) friendComboBox.getSelectedItem();
            String message = inputField.getText();
            if (!message.isEmpty()) {
                JSONObject msgJson = new JSONObject();
                msgJson.put("type", "friend_message");
                msgJson.put("sender_id", "123");
                msgJson.put("receiver_id", "456");
                msgJson.put("message_data", message);
                msgJson.put("sent_time", new java.util.Date().toString());

                try {
                    String encrypted = AESUtil.encrypt(msgJson.toString());
                    NetworkClient.send(encrypted);
                    chatArea.append("我(" + selectedFriend + "): " + message + "\n");
                    inputField.setText("");
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(frame, "发送失败: " + ex.getMessage());
                }
            }
        });

        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.add(inputField, BorderLayout.CENTER);
        bottomPanel.add(sendButton, BorderLayout.EAST);

        frame.add(topPanel, BorderLayout.NORTH);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.add(bottomPanel, BorderLayout.SOUTH);
        frame.setVisible(true);
    }
}
